package com.xbang.attendance.web.action.system.sign2;

import java.io.UnsupportedEncodingException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.demo2do.lighturl.annotation.Action;
import com.xbang.attendance.entity.Sign.Actioninfo;
import com.xbang.attendance.entity.Sign.detail;
import com.xbang.attendance.service.AnalyseDataService;
import com.xbang.attendance.service.SystemService;
import com.xbang.attendance.service.impl.AnalyseDataServiceImpl;
import com.xbang.core.page.Result;
import com.xbang.core.struts.support.SearchActionSupport;

public class Index extends SearchActionSupport {

	@Autowired
	private SystemService systemService;
	
	

	private  AnalyseDataService analyseDataService;
	
	public AnalyseDataService getAnalyseDataService() {
		return analyseDataService;
	}

	public void setAnalyseDataService(AnalyseDataService analyseDataService) {
		this.analyseDataService = analyseDataService;
	}

	public SystemService getSystemService() {
		return systemService;
	}

	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	public List<detail> getDetails() {
		return details;
	}

	public void setDetails(List<detail> details) {
		this.details = details;
	}

	private List<detail> details = new ArrayList<detail>();
	
	public boolean validate_com = false; //公司签到开关
	public boolean validate_out = false;  //外勤签到开关
	public Map comMap =  new HashMap();
	public Map outMap = new HashMap();
	public void newsaveData(Map map,String useId,Map parameters){
		validate_com = false; //公司签到开关
		validate_out = false;  //外勤签到开关	
	    String	sql = "SELECT * FROM  actioninfo WHERE user_id ='"+useId+"' AND signin_time>('"+map.get("date")+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+map.get("date")+"' ORDER BY signin_time ASC";
	    List<Map> listmap=systemService.queryForList(sql, parameters);
		 comMap =  new HashMap();
		 comMap.clear();
		 outMap = new HashMap();
		 outMap.clear();
		 analyseDataService = new AnalyseDataServiceImpl();
		 try {		
			 List<Actioninfo>  actions=	 analyseDataService.loadOriDatas(listmap);
			 analyseDataService.analyseData(useId, actions);
			 
			//analyseDataService.analyseData(useId, actionInfos);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    for(Map dataMap :listmap){
	    	InsertDetail(dataMap,map);
	    }
	    
	}
   
	public void InsertDetail(Map dataMap,Map map){	
	/*	 //父类型,               //子类型
	      公司签到：00；    ｛我来了:00、我走了:01、晚到:02  ｝
	      外勤签到：01；    ｛我开工了: 10，我收工了:11，到了: 12 ，走了: 13 ｝
	      请假：02 ；          {年假:20、病假:21、调休:22、事假:23}
		//外勤或者公司考勤模式，父类型  */
		String attModel =dataMap.get("action_type")!=null?String.valueOf(dataMap.get("action_type")):null;
		//子类型
		String attSubModel =dataMap.get("action_sub_type")!=null?String.valueOf(dataMap.get("action_sub_type")):null;	
		
		if (validate_com || validate_out){
			if (validate_com){
				//
				if ("00".equals(attModel) && "01".equals(attSubModel) && validate_com){ //attModel = '公司签到' && attSubModel = '我走了' && validate_com
					//正常
					//validate_com补充离开时间	
					if(comMap.get("detail")!=null){
						detail	detail = (detail) comMap.get("detail");
						try {
							detail=	insertout(null, map, attModel, "03", null,  detail, dataMap);
							systemService.save(detail);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						comMap.put("detail", detail);//将后半部分的detail一起放在comMap中						
					}
					validate_com = false;
					validate_out = false;
					outMap.clear();
					//outMap = new HashMap(); 
					//继续
				} else if ("01".equals(attModel)&&"10".equals(attSubModel)&& !validate_out){ //attModel = '外勤') && (attSubModel='开工'
					//
				   //保存公司走了了相关数据
				   //初始化comMap
				   //初始话outMap
					outMap = new HashMap(); 
					detail detail= new detail();
					detail =	Insertrowon(null, map, null, dataMap, "01", detail); //我来了的信息存入detail对象中
					outMap.put("detail",detail);
					validate_out = true;					
				}
			}  
			if (validate_out){
				//
				if ("00".equals(attModel)&&"00".equals(attSubModel) && !validate_com){//attModel = '公司签到' && attSubModel = '我来了' && !validate_com
					//正常
					comMap = new HashMap(); 
					detail detail= new detail();
					detail =	Insertrowon(null, map, null, dataMap, "00", detail); //我来了的信息存入detail对象中
					outMap.put("detail",detail);
					validate_out = true;
					validate_com = true;
				} else if ("01".equals(attModel)&&"11".equals(attSubModel)){ //(attModel = '外勤') && (attSubModel='收工')
					//validate_out补充收工时间外勤考勤数据
					if(outMap.get("detail")!=null){
						detail	detail = (detail) outMap.get("detail");
						try {
							detail=	insertout(null, map, attModel, "03", null,  detail, dataMap);
							systemService.save(detail);
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						outMap.put("detail", detail);//将后半部分的detail一起放在comMap中
					}
					validate_out = false;
					validate_com = false;
					comMap.clear();
					//继续
					
				}
			}
		} else if ("01".equals(attModel)&&"10".equals(attSubModel)){//(attModel = '外勤') && (attSubModel='开工')) 
	
				outMap = new HashMap();				
				detail detail= new detail();
				detail =	Insertrowon(null, map, null, dataMap, "01", detail); //收工的信息存入detail对象中
				outMap.put("detail",detail);
				validate_out = true;
			//}
			//初始化outMap
			
		} else if ("00".equals(attModel)&&"00".equals(attSubModel)){//((attModel = '公司签到') && (attSubModel='我来了'))
			//初始化comMap
	
				comMap = new HashMap();
				detail detail= new detail();
				detail =	Insertrowon(null, map, null, dataMap, "00", detail); //我来了的信息存入detail对象中
				comMap.put("detail",detail);
				validate_com = true; //  公司签到开。
		//	}
		
		
		} else if ("01".equals(attModel)&&"11".equals(attSubModel)){//(attModel = '外勤') && (attSubModel='收工')
			//
		    if(!outMap.isEmpty()){
			detail detail =	(detail) outMap.get("detail");
		    String endtime=	detail.getGpsEndtime();
			if (!outMap.isEmpty()&&"".equals(endtime)&&endtime!=null){
				//补充compMap最后的数据
				try {
					detail=	insertout(null, map, attModel, "03", null,  detail, dataMap);
					systemService.update(detail);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				outMap.put("detail", detail);//将后半部分的detail一起放在comMap中
			}
		  }
		}else if ("00".equals(attModel)&&"01".equals(attSubModel)){//comMap有走了时间
			//
			if(!comMap.isEmpty()){
			detail detail =	(detail) comMap.get("detail");
		    String endtime=	detail.getGpsEndtime();
			if (!comMap.isEmpty()&&!"".equals(endtime)&&endtime!=null){
				//补充compMap最后的数据
				try {
					detail=	insertout(null, map, attModel, "03", null, detail, dataMap);
					systemService.update(detail);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				comMap.put("detail", detail);//将后半部分的detail一起放在comMap中
			}
			}
		
			
		} else {
			
		
			if (true){//outMap有收工时间
					//保存外勤;
					//outMap = new HashMap();
				} else {
					//保存公司;
					//comMap = new HashMap();
				}
		}
	}
	   
	/**@param  存储签出原始数据
	 * @param datemap     原始数据中所有日期
	 * @param map  用户和组织，企业位置gps相关信息
	 * @param sql
	 * @param listmap  数据集合
	 * @param type  签到类型
	 */
	public void savedata(){
		//根据用户，时间日期。找到同一天内，在同一企业位置的有效范围内，
		//整合这天签到时间最小的“我来了”的签到信息，和这天签到时间最大的“我走了”的签到信息
		//，“我来了”和“我走了”必须成对出现。并且“我走了”的时间要比“我来了”的时间要大，如果有“晚到”原始数据要把晚到相关信息也整合到该条数据中
		Map parameters =  new HashMap<String, String>();
		Map datemap =new HashMap<String, String>();
		// String maxDate = MaxDate();		
		try {		
			String	sql = " SELECT * FROM userinfo";
		    List <Map> list=systemService.queryForList(sql, parameters);
		    if(list.size()>0&&list!=null){
		    	for(Map map : list){
		    	String useId =	String.valueOf( map.get("user_id")!=null? map.get("user_id").toString():"");
		        String name = String.valueOf( map.get("department")!=null? map.get("department").toString():"");
		    	sql = " SELECT departname FROM department where id='"+name+"'";
		    	 List <Map> listdepart=systemService.queryForList(sql, parameters);
		    	 map.put("departname", listdepart.get(0).get("departname"));
		    	 datemap  = getdate(useId,parameters);//公司签到所有日期集合\
		    		if(datemap.size()>0&&datemap!=null){
						 Set set = datemap.entrySet();
					        for (Iterator<Map.Entry> it = set.iterator(); it.hasNext();) {  //根据日期循环 ，返回			每天一个人这能返回一条外勤签到信息。 或者返回一条公司签到	或者 外勤签到,公司签到各返回一条	        	
					            Map.Entry entry = (Map.Entry) it.next();
					        	String date =(String) entry.getValue();
					        	map.put("date", date);
					        	
//					        	 detail companydetail = Insertrow(parameters, datemap, map, useId,"00","00","01","02");//公司签到						    	 
//						    	 detail outdetail= Insertrow(parameters, datemap, map, useId,"01","10","11","12");//外勤签到
//						    	 
//						    	 if(companydetail!=null&&outdetail==null){
//						    		 systemService.save(companydetail);
//						    	 }else if(companydetail==null&&outdetail!=null){
//						    		 systemService.save(outdetail);
//						    	 }else if(companydetail!=null&&outdetail!=null){
//						    		 long timeocEnd  =	getdate(outdetail.getGpsEndtime(),companydetail.getGpsStarttime()); //先外勤,后去公司
//						    		 long timeocStar = getdate(outdetail.getGpsStarttime(),companydetail.getGpsStarttime());
//						    		 long timecoEnd =	getdate(companydetail.getGpsEndtime(),outdetail.getGpsStarttime());  //先公司,后去外勤
//						    		 long timecoSta = getdate(companydetail.getGpsStarttime(),outdetail.getGpsStarttime());
//						    		 if(timeocEnd<0&&timeocStar<0||timecoEnd<0&&timecoSta<0){
//						    			 systemService.save(outdetail);
//						    			 systemService.save(companydetail);
//						    		 }
//						    	 }
					    	 newsaveData(map, useId, parameters);
					        	
						    	 sql = "select * FROM  actioninfo WHERE action_type='02' and  user_id='"+useId+"'and signin_time >'"+maxDate+" 00:00:00'AND signin_time>('"+map.get("date")+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+map.get("date")+"'";
						    	 Insertrow(parameters,map,sql);                                               //请假 （只要是请假全过，没有请假规则）
					        	
					        }
		    		}
		    	 
		    			    	
		    	}
		    	
		    }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	 /**
	  * @param 返回明细最后统计的日期
	  *  
	  *  */
	public String MaxDate(){
		 String sql;
			sql = "select max(date) FROM  detail ";
			List <Map> company=systemService.queryForList(sql, new HashMap<String, String>()); 
		    String MaxDate =String.valueOf(company.get(0).get("max(date)")!=null?company.get(0).get("max(date)"):"1979-01-01") ;
		    return  MaxDate;
	}
 /**
  * @param 返回原始数据 签到日期
  *  
  *  */
   public Map getdate(String useId,Map parameters ){
	   
	   Map  datemap = new HashMap<String, String>();
	 
	   String sql;
		sql = "select * FROM  actioninfo WHERE  user_id ='"+useId+"' and signin_time >'"+maxDate+" 00:00:00'";
		//，我来了的所有信息
		List <Map> company=systemService.queryForList(sql, parameters); 
		if(!company.isEmpty()){
			for(Map date : company){
		    	String date1 =date.get("signin_time").toString().substring(0, 10); //签到日期  年-月-日
		    	if(!"".equals(date1)&&date1!=null){
		    		datemap.put(date1, date1);		    		
		    	}
			}
		}	
	  
		return datemap;
   }
   /**
    * @param 判断 该签到的gps坐标是否在特定企业坐标有效范围类
    * @param    locLongtitude  经度
    * @param    locLatitude    纬度
    *  */
   
   public  boolean returngps(String locLongtitude,String locLatitude,Map parameters){
	 String sql ="SELECT  *  FROM company_gps  WHERE company_id ='main'";           
	 String specificX = "0";  //特定纬度
	 String specificY= "0";  //特定经度
	 String scopeid ="-1";
	 List <Map> companygps=systemService.queryForList(sql, parameters);  
	 if(!companygps.isEmpty()){
			for(Map gps : companygps){
				 specificX =gps.get("locLatitude").toString();   
				 specificY =gps.get("locLongtitude").toString();
				 scopeid = gps.get("scope").toString();
			}
		}	 
	 Double dspecificx =Double.parseDouble(specificX);	  //特定纬度
	 Double dspecificY = Double.parseDouble(specificY);   //特定经度
	 Double dlocLongtitude = Double.parseDouble(locLongtitude); //待判断经度 
	 Double dlocLatitude = Double.parseDouble(locLatitude);    //待判断纬度
	 //=SQRT(ABS((C2-F2)*(C2-F2)*115.78947368*115.78947368+(B2-E2)*(B2-E2)*86.666667*86.666667))  已知俩点经纬度求这俩点直接的实际距离（米）	 
     double math =	 Math.abs((dlocLatitude-dspecificx)*(dlocLatitude-dspecificx)*115.78947368*115.78947368+(dlocLongtitude-dspecificY)*(dlocLongtitude-dspecificY)*86.666667*86.666667);//求绝对值
	 double d=Math.sqrt(math);
	 sql = "SELECT  scopedistance  FROM scope WHERE id = '"+scopeid+"'";
	 List <Map> scopedistance =systemService.queryForList(sql, parameters);
	 String distance = "";
	 if(!scopedistance.isEmpty()){
		 distance =  scopedistance.get(0).get("scopedistance")!=null?String.valueOf(scopedistance.get(0).get("scopedistance")):"";
	 }
	 double distancedb = Double.parseDouble(distance);
	 
	 if(d<=distancedb){
		return true;
	 }else{
		return  false;
	 }
	 //有效范围
	
   }
    
   private  String maxDate=null;
   
	@Action("/system/sign2/list")
	public String list(){
		maxDate =MaxDate();
		Map map1= new HashMap();
		String hqlSentence = "FROM detail detail WHERE 1 = 1 ";

		if (searchComponent.getOrderParameters().isEmpty()) {
			searchComponent.addSearchElement("orderBy.detail.date", "DESC");
		}

	if (page != null) {
			if (currPageId.intValue() != -1 && currPageId.intValue() > 0) {
				page.setCurrentPage(currPageId);
			}
		}
	
		Result result = systemService.searchByPage(hqlSentence, searchComponent, page);	
	    details = result.getItems();
		page = result.getPage();
		
		String   sql = "delete from detail where date='"+maxDate+"'";
			try {
				systemService.execute(sql, null);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		savedata();
		return "index";
	}
	   
	/**@param  存储签出原始数据
	 * @param parameters
	 * @param map  用户和组织相关信息
	 * @param sql
	 * @param listmap  数据集合
	 * @param type  签到类型
	 */
		private void Insertrowout( Map parameters,Map map,String sql,List<Map> listmap,String type) {
			// TODO Auto-generated method stub
			 // List <Map> Qj=systemService.queryForList(sql,parameters); 
		         for(Map detailclass : listmap){
		     	if(!detailclass.isEmpty()){
		     		detail detail = new detail();
		     		detail.setDepartment(null);
		     		String	endTime =
		     				String.valueOf(detailclass.get("Max(signin_time)")!=null?String.valueOf(detailclass.get("Max(signin_time)")):"");
	             	String endtimedate = endTime;
	             	detail.setGpsEndtime(endTime);
			        	detail.setUserName(map.get("user_name").toString());
			        	detail.setDepartment(String.valueOf( map.get("departname"))!=null? map.get("departname").toString():"");
			        	String date =detailclass.get("signin_time").toString().substring(0, 10);
			        	detail.setDate(date);
			            detail.setType("");
			            if("00".equals(type)){
	 		        		detail.setType("公司签到");
	 		        	}else if ("01".equals(type)){
	 		        		detail.setType("外勤签到");
	 		        	}
			        	detail.setLateTime(String.valueOf(detailclass.get("late_time")!=null? detailclass.get("late_time").toString():""));
			        	try {
							detail.setOutAddress(String.valueOf(detailclass.get("address")!=null?java.net.URLDecoder.decode( detailclass.get("address").toString(),"utf-8"):""));
						} catch (UnsupportedEncodingException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}//address
			        	detail.setRecordOuttime(String.valueOf(detailclass.get("signin_time")!=null? detailclass.get("signin_time").toString():""));//signin_time
			        	detail.setDistance(String.valueOf(detailclass.get("distance")!=null? detailclass.get("distance").toString():""));//deviceIddistance
			        	detail.setDeviceId(String.valueOf(detailclass.get("device_id")!=null? detailclass.get("device_id").toString():""));//	device_id	    		  
			        	detail.setDevicenum(String.valueOf(detailclass.get("device_type")!=null? detailclass.get("device_type").toString():""));//device_type
			           try {
						systemService.save(detail);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
		     	}
		     	}
		}
		
		/**@param  存储签入原始数据
		 * @param parameters
		 * @param map  用户和组织相关信息
		 * @param sql
		 * @param listmap  数据集合
		 * @param type  签到类型
		 */
			private detail Insertrowon( Map parameters,Map map,String sql,Map detailclass,String actionType,detail detail ) {
			         
	 		    		        	detail.setDepartment(null);
	 		    		        	detail.setUserName(map.get("user_name").toString());
	 		    		        	detail.setDepartment(String.valueOf( map.get("departname"))!=null? map.get("departname").toString():"");
	 		    		        	String date = String.valueOf( map.get("date"))!=null? map.get("date").toString():"";
	 		    		        	detail.setDate(date);
	 		    		        	if("00".equals(actionType)){
	 		    		        		detail.setType("公司签到");
	 		    		        	}else if ("01".equals(actionType)){
	 		    		        		detail.setType("外勤签到");
	 		    		        	}			 		    		        	
	 		    		        	String startTime = detailclass.get("signin_time").toString(); //String startTime = detailclass.get("min(signin_time)").toString();
	 		    		        	detail.setGpsStarttime(startTime);
	 		    		            long lateor =	getdate(startTime,date+" 09:30:00");
	 		    		        	if(lateor<60*30){
	 		    		            detail.setLateor("是");
	 		    		        	}else{
	 		    		        	detail.setLateor("否");	
	 		    		        	}
	 		    		      
	 				        	try {
									detail.setOnAddress(String.valueOf(detailclass.get("address")!=null&&!"null".equals(detailclass.get("address"))?java.net.URLDecoder.decode( detailclass.get("address").toString(),"utf-8"):""));
								} catch (UnsupportedEncodingException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}//address
	 				        	detail.setRecordOntime(String.valueOf(detailclass.get("signin_time")!=null? detailclass.get("signin_time").toString():""));//signin_time
	 				        	detail.setDistance(String.valueOf(detailclass.get("distance")!=null? detailclass.get("distance").toString():""));//deviceIddistance
	 				        	detail.setDeviceId(String.valueOf(detailclass.get("device_id")!=null? detailclass.get("device_id").toString():""));//	device_id	    		  
	 				        	detail.setDevicenum(String.valueOf(detailclass.get("device_type")!=null? detailclass.get("device_type").toString():""));   //device_type
	 			
			  	                return detail;
			}
			
		/**@param 插入签入信息     无条件储存请假原始数据  
		 * @param parameters
		 * @param map  用户和组织相关信息
		 * @param sql
		 */
		private  void Insertrow( Map parameters,Map map,String sql) {
			// TODO Auto-generated method stub
	        
	         List <Map> Qj=systemService.queryForList(sql,parameters); 
	         for(Map detailclass : Qj){
	     	if(!detailclass.isEmpty()){
	     		detail detail = new detail();
	     		detail.setDepartment(null);
		        	detail.setUserName(map.get("user_name").toString());
		        	detail.setDepartment(String.valueOf( map.get("departname"))!=null? map.get("departname").toString():"");
		        	String date =String.valueOf(detailclass.get("signin_time")!=null? detailclass.get("signin_time").toString():"");//detailclass.get("signin_time").toString().substring(0, 10);
		        	detail.setDate(date.substring(0, 10));
		            detail.setType("请假");
		        	String startTime =String.valueOf(detailclass.get("gps_time")!=null? detailclass.get("gps_time").toString():""); //detailclass.get("gps_time").toString();
		        	detail.setGpsStarttime(startTime);
		        	detail.setLateTime(String.valueOf(detailclass.get("late_time")!=null? detailclass.get("late_time").toString():""));
		        	try {
						detail.setOnAddress(String.valueOf(detailclass.get("address")!=null?java.net.URLDecoder.decode( detailclass.get("address").toString(),"utf-8"):""));
					} catch (UnsupportedEncodingException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}//address
		        	detail.setRecordOntime(String.valueOf(detailclass.get("signin_time")!=null? detailclass.get("signin_time").toString():""));//signin_time
		        	detail.setDistance(String.valueOf(detailclass.get("distance")!=null? detailclass.get("distance").toString():""));//deviceIddistance
		        	detail.setDeviceId(String.valueOf(detailclass.get("device_id")!=null? detailclass.get("device_id").toString():""));//	device_id	    		  
		        	detail.setDevicenum(String.valueOf(detailclass.get("device_type")!=null? detailclass.get("device_type").toString():""));//device_type
		           try {
		        	   systemService.save(detail);    
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
	     	}
	     	}
		}
		/**
		 * @param parameters
		 * @param datemap
		 * @param map
		 * @param useId
		 * @param actionType
		 * @throws Exception
		 */
		private detail Insertrow(Map parameters, Map datemap, Map map, String useId,String actionType,String onactionSubType,String outactionSubType,String lateactionSubType)
				throws Exception {
			String sql;
			 detail detail = new detail();
				         
				            sql = "SELECT *,min(signin_time) FROM  actioninfo WHERE action_type='"+actionType+"' AND action_sub_type ='"+onactionSubType+"' AND user_id ='"+useId+"' AND signin_time>('"+map.get("date")+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+map.get("date")+"'";
				            List <Map> checkon=systemService.queryForList(sql, parameters);
				            if(!checkon.isEmpty()){				            	
				            	 for(Map detailclass : checkon){ //签到明细对象的部分数据（我来了）
				            		 if(detailclass.get("min(signin_time)")!=null){
				            			
				            			 detail =   Insertrowon(parameters, map, sql, detailclass, actionType, detail);			 		    		        	
			 		    		        	//我走了			 
			 		    		        	sql="SELECT *,Max(signin_time) FROM  actioninfo WHERE action_type='"+actionType+"' AND action_sub_type ='"+outactionSubType+"' AND user_id ='"+useId+"' AND signin_time>('"+map.get("date")+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+map.get("date")+"'";	  
			 		    		        	List <Map> checkout=systemService.queryForList(sql, parameters);
			 	    		                if(checkout.size()>0&&checkout!=null&&!checkout.isEmpty()){
			 	    		                	Map mapchekout = checkout.get(0);
	
			 	    		                	if(mapchekout.get("Max(signin_time)")!=null){
			 	    		                		String	endTime = mapchekout.get("Max(signin_time)").toString();
				 	    		                	String endtimedate = endTime;
				 	    		                	detail.setGpsEndtime(endTime);
				 	    		                	detail.setOutAddress(String.valueOf(mapchekout.get("address")!=null&&!"null".equals(mapchekout.get("address"))?java.net.URLDecoder.decode( mapchekout.get("address").toString(),"utf-8"):""));//address
						 				        	detail.setRecordOuttime(String.valueOf(mapchekout.get("signin_time")!=null? mapchekout.get("signin_time").toString():""));//signin_time
				 	    		                	//晚到
				 	    		                	sql="SELECT *,Max(signin_time) FROM  actioninfo WHERE action_type='"+actionType+"' AND action_sub_type ='"+lateactionSubType+"' AND user_id ='"+useId+"' AND signin_time>('"+map.get("date")+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+map.get("date")+"'";
				 	    		                	List <Map> late=systemService.queryForList(sql, parameters);
				 	    		                	if(late.size()>0&&late!=null&&!late.isEmpty()){
				 	    		                		Map latemap = late.get(0);
				 	    		                		if(!latemap.isEmpty()&& latemap.get("id")!=null&&latemap.get("Max(signin_time)")!=null){
				 	    		                			detail.setLateTime(String.valueOf(latemap.get("late_time")!=null? latemap.get("late_time").toString():""));
		
				 	    		                			}
				 	    		                		  		                		
				 	    		                	}else{
				 	    		                		System.out.print("没有迟到信息");
				 	    		                	}
				 	    		                long hour =   getdate(detail.getGpsEndtime(),detail.getGpsStarttime());
				 	    		                if(hour>=0){
				 	    		                	String hourStr =String.valueOf(hour);
				 	    		                	  detail.setWorkHour(hourStr);	
				 	    		                	  return detail;
						 	    		             // systemService.save(detail); 
				 	    		                }	                	
				 	    		                  }   
			 	    		            /*    	else{  
				 	    		                	  // 外勤或公司签到
				 	    		                		comOrout(parameters,
																map, useId,
																actionType,
																date, detail);				 	    		                					 	    		                	
				 	    		                  }*/
			 	    		                	
				 	    		                }			 	    		           	 
					            		 }
				    		        
			                	}
			 	    		                	
					            
					        }	 

				            return null;
				            	
		}
  
		private detail insertout(Map parameters, Map map, 
				String actionType, String lateactionSubType, String sql,
				detail detail, Map mapchekout)
				throws UnsupportedEncodingException {
			if(mapchekout.get("signin_time")!=null){
				String	endTime = mapchekout.get("signin_time").toString();
				String endtimedate = endTime;
				detail.setGpsEndtime(endTime);
				detail.setOutAddress(String.valueOf(mapchekout.get("address")!=null&&!"null".equals(mapchekout.get("address"))?java.net.URLDecoder.decode( mapchekout.get("address").toString(),"utf-8"):""));//address
				detail.setRecordOuttime(String.valueOf(mapchekout.get("signin_time")!=null? mapchekout.get("signin_time").toString():""));//signin_time
				//晚到
				sql="SELECT *,signin_time FROM  actioninfo WHERE action_type='"+actionType+"' AND action_sub_type ='"+lateactionSubType+"' AND user_id ='"+map.get("user_id").toString()+"' AND signin_time>('"+map.get("date")+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+map.get("date")+"'";
				List <Map> late=systemService.queryForList(sql, parameters);
				if(late.size()>0&&late!=null&&!late.isEmpty()){
					Map latemap = late.get(0);
					if(!latemap.isEmpty()&& latemap.get("id")!=null&&latemap.get("signin_time")!=null){
						detail.setLateTime(String.valueOf(latemap.get("late_time")!=null? latemap.get("late_time").toString():""));

						}
					  		                		
				}else{
					System.out.print("没有迟到信息");
				}
			long hour =   getdate(detail.getGpsEndtime(),detail.getGpsStarttime());
			if(hour>=0){
				String hourStr =String.valueOf(hour);
				  detail.setWorkHour(hourStr);	
				  return detail;
			     // systemService.save(detail); 
			}	                	
			  }
			return detail;
		}

		
		private void comOrout(Map parameters, Map map, String useId,
				String actionType, String date, detail detail) throws Exception {
			
			
			
			String sql;
			if("00".equals(actionType)){
				  System.out.println("本次没有公司签出记录，可能在外勤");
				  sql="SELECT *,Max(signin_time) FROM  actioninfo WHERE action_type='01' AND action_sub_type ='11' AND user_id ='"+useId+"' AND signin_time>('"+date+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+date+"'";
				  List <Map>  selectList =systemService.queryForList(sql, parameters);
				  if(selectList.size()>0&&selectList!=null&&selectList.get(0).get("Max(signin_time)")!=null){
					  systemService.save(detail);  
					  String type ="01";
					 Insertrowout(null, map, sql,selectList,type);
				  }
			}else if ("01".equals(actionType)){
				  System.out.println("本次没有公司签出记录，可能在外勤");
				  sql="SELECT *,Max(signin_time) FROM  actioninfo WHERE action_type='00' AND action_sub_type ='01' AND user_id ='"+useId+"' AND signin_time>('"+date+"'  - INTERVAL 1 SECOND) AND  signin_time< INTERVAL 1 DAY + '"+date+"'";
				  List <Map>  selectList =systemService.queryForList(sql, parameters);
				  if(selectList.size()>0&&selectList!=null&&selectList.get(0).get("Max(signin_time)")!=null){
					  systemService.save(detail);   
					  String type = "00";
					 Insertrowout(null, map, sql,selectList, type);
				  }
			}
		}
	   
		public long getdate(String d1, String d2) {
			   long i = -1;
			   try {
			    SimpleDateFormat formatter = new SimpleDateFormat(
			      "yyyy-MM-dd HH:mm:ss");
			    ParsePosition pos = new ParsePosition(0);
			    ParsePosition pos1 = new ParsePosition(0);
			    Date dt1 = formatter.parse(d1, pos);
			    Date dt2 = formatter.parse(d2, pos1);
			    long l = dt1.getTime() - dt2.getTime();
			    i = l / (1000 * 60 * 60 );
			    // 这是他们相差的天数。
			    System.out.println("Hello World!=" + i);
			    
			   } catch (Exception e){
				}
			   return i;
			   }
		
	
	@Override
	public void resetCustomerSearchCriteria() {
		// TODO Auto-generated method stub
		
	}
  
	 
}
